package com.lagou.edu.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * IP 防刷工具类， 1分钟内只最多允许100次用户操作
 * 每次启动不需要清除缓存数据
 */
@Component
public class IpFlushFirewall {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 最大ip限制次数
     */
    private static int maxLimitIpHit = 100;

    /**
     * 检查时效,单位:秒
     */
    private static int checkLimitIpHitInterval = 60;

    // 测试访问的方法
    public Object testLoginAction(Object req) {
        // ip防刷
        String reqIp = "127.0.0.1";
        checkIpLimit(reqIp);
        // 用户信息校验
        System.out.println("login success...");
        // 返回用户信息
        return null;
    }

    // 检测限制入口
    private void checkIpLimit(String ip) {
        if (isIpLimited(ip)) {
            throw new RuntimeException("操作频繁，请稍后再试！");
        }
    }

    // ip 防刷 / 使用切面进行拦截
    //@Before(value = "execution(public * com.*.*.*(..))")
    public void checkIpLimit() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String ip = getIp(request);
        if (isIpLimited(ip)) {
            throw new RuntimeException("操作频繁，请稍后再试！");
        }
    }

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多级代理问题
        if (ip.contains(",")) {
            ip = ip.substring(0, ip.indexOf(',')).trim();
        }
        return ip;
    }

    /**
     * 判断ip是否受限制, 非核心场景，对于非原子的更新计数问题不大，否则考虑使用分布式锁调用更新
     */
    public boolean isIpLimited(String reqIp) {
        String ipHitCache = getIpHitCacheKey(reqIp);
        // 先取旧数据作为本次判断，再记录本次访问
        String hitsStr = redisTemplate.opsForValue().get(ipHitCache);
        recordNewIpRequest(reqIp);
        // 新周期内，首次访问
        if (hitsStr == null) {
            return false;
        }
        // 之前有命中
        // 总数未超限，直接通过
        if (!isOverMaxLimit(Integer.valueOf(hitsStr) + 1)) {
            return false;
        }
        // 当前访问后超过限制后，再判断周期内的数据
        Long retainIpHits = countEffectiveIntervalIpHit(reqIp);
        // 重新设置个数
        redisTemplate.opsForValue().set(ipHitCache, retainIpHits + "");
        // 将有效计数更新回计数器,删除无效计数后，在限制范围内，则不限制操作
        if (!isOverMaxLimit(retainIpHits.intValue())) {
            return false;
        }
        return true;
    }

    // 是否超过最大限制
    private boolean isOverMaxLimit(Integer nowCount) {
        return nowCount > maxLimitIpHit;
    }

    // 每次访问必须记录
    private void recordNewIpRequest(String reqIp) {
        if (redisTemplate.hasKey(getIpHitCacheKey(reqIp))) {
            // 自增访问量
            redisTemplate.opsForValue().increment(getIpHitCacheKey(reqIp));
        } else {
            redisTemplate.opsForValue().set(getIpHitCacheKey(reqIp), "1");
        }
        redisTemplate.expire(getIpHitCacheKey(reqIp), checkLimitIpHitInterval, TimeUnit.SECONDS);

        Long nowTime = System.currentTimeMillis();
        // 使用 sorted set 保存记录时间，方便删除, zset 元素尽可能保持唯一，否则会导致统计有效时数据变少问题
        redisTemplate.opsForZSet().add(getIpHitStartTimeCacheKey(reqIp), reqIp + "-" + System.nanoTime() + Math.random(), nowTime);
        redisTemplate.expire(getIpHitStartTimeCacheKey(reqIp), checkLimitIpHitInterval, TimeUnit.SECONDS);
    }

    /**
     * 统计计数周期内有效的的访问次数（删除无效统计）
     *
     * @param reqIp 请求ip
     * @return 有效计数
     */
    private Long countEffectiveIntervalIpHit(String reqIp) {
        // 删除统计周期外的计数
        Long nowTime = System.currentTimeMillis();
        Long endTime = nowTime - (checkLimitIpHitInterval * 1000);
        redisTemplate.opsForZSet().removeRangeByScore(getIpHitStartTimeCacheKey(reqIp), 0, endTime);
        // 统计剩余个数
        return redisTemplate.opsForZSet().size(getIpHitStartTimeCacheKey(reqIp));
    }

    // ip 访问计数器缓存key
    private String getIpHitCacheKey(String reqIp) {
        return "secure.ip.limit." + reqIp;
    }

    // ip 访问开始时间缓存key
    private String getIpHitStartTimeCacheKey(String reqIp) {
        return "secure.ip.limit." + reqIp + ".starttime";
    }

}
